<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app'
import {ref} from "vue"

interface TrainingDetail {
  id: string
  trainingId: string
  trainingTheme: string
  workEndTime: string
  workRequire: string
  [key: string]: any
}
import {
  addHomework,
  getDictType,
  getHomeworkList,
  getTrainingCourseById,
  getTrainingCourseStatus,
  uploadFile
} from "../../api/training";
import {token} from "../../stores/user";
import { BASE_URL } from "../../utils/request";

const id = ref({})
const startTime = ref('')
const showStartTimeButton = ref(true)
const showEndTimeButton = ref(true)

onLoad(async (options) => {
  id.value = options.id
  startTime.value = options.startTime || ''

  await getDetail()
  homeworkList()
  getStatus()

  const now = new Date()
  now.setHours(0, 0, 0, 0)
  console.log("当前时间 - now:", now)

  // 检查开始时间：如果startTime为空则默认展示，否则判断是否小于当前时间
  let startTimeValid = true
  if (startTime.value) {
    const startDate = new Date(startTime.value)
    startDate.setHours(0, 0, 0, 0)
    console.log("课程开始时间 - startTime:", startDate)
    startTimeValid = startDate <= now
  }

  // 检查截止时间是否大于当前时间
  let endTimeValid = true

  if (detail.value?.workEndTime) {
    const endDate = new Date(detail.value.workEndTime)
    endDate.setHours(0, 0, 0, 0)
    console.log("作业截止时间 - workEndTime:", endDate)
    endTimeValid = now <= endDate
  }

  showStartTimeButton.value = startTimeValid
  showEndTimeButton.value = endTimeValid
  console.log("时间验证结果 - startTimeValid:", startTimeValid, "endTimeValid:", endTimeValid)
})

const detail = ref<TrainingDetail>({} as TrainingDetail)
const courseStatus = ref({})
const workList = ref([])


function getStatus() {
  getTrainingCourseStatus(id.value as string).then(res => {
    courseStatus.value = res.data || {}
  })
}

async function getDetail() {
  if (!id.value) return
  const ret = await getTrainingCourseById(id.value as string)
  detail.value = ret.data
}

function homeworkList() {
  getHomeworkList(id.value).then(res => {
    workList.value = res.data
  })
}

const resourceUrl = ref('')
const resourceUrlName = ref('')

function upload() {
  uni.chooseMessageFile({
    count: 1, // 可选择文件数量
    type: 'file', // 类型为文件
    success: (chooseRes) => {
      const tempFiles = chooseRes.tempFiles[0]
      uni.uploadFile({
        url: `${BASE_URL}/file/upload`,
        filePath: tempFiles.path,
        name: 'file',
        header: {
          "third-session": token.value,
        },
        success: res => {
          const ret = JSON.parse(res.data)
          resourceUrl.value = ret.data.url
          resourceUrlName.value = tempFiles.name
        },
        fail: err => {
          console.log(err, '上传失败')
        }
      })
    },
    fail: (err) => {
      console.error('选择图片失败', err)
    }
  })
}
function handleDownload(url) {
  handleDownloadFile(url)
}

/**
 * 根据 URL 自动解析文件名
 * @param {string} url
 * @param {string} defaultExt - 默认后缀（如 'pdf'）
 * @returns {string} fileName
 */
function parseFileNameFromUrl(url, defaultExt = 'pdf') {
  try {
    const decodeUrl = decodeURIComponent(url.split('?')[0])
    const parts = decodeUrl.split('/')
    let fileName = parts[parts.length - 1]
    return fileName
  } catch (e) {
    return ``
  }
}

/**
 * 下载并处理网络文件（图片/视频/文档）
 * @param {string} url - 网络文件地址
 * @param {string} fileName - 可选，下载时保存的文件名
 */
function handleDownloadFile(url) {
  const fileName = parseFileNameFromUrl(url)

  const suffix = fileName.split('.').pop().toLowerCase()
  const isImage = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'].includes(suffix)
  const isVideo = ['mp4', 'avi', 'mov', 'mkv', 'webm'].includes(suffix)

  uni.showLoading({ title: '下载中...' })
  uni.downloadFile({
    url,
    success: (res) => {
      if (res.statusCode === 200) {
        const tempPath = res.tempFilePath
        if (isImage) {
          uni.saveImageToPhotosAlbum({
            filePath: tempPath,
            success: () => uni.showToast({ title: '图片已保存' }),
          })
        } else if (isVideo) {
          uni.saveVideoToPhotosAlbum({
            filePath: tempPath,
            success: () => uni.showToast({ title: '视频已保存' }),
          })
        } else {
          uni.openDocument({
            filePath: tempPath,
            fileType: suffix,
          })
        }
      }
    },
    fail: (e) => {
      console.error('下载失败', e)
    },
    complete: () => {
      uni.hideLoading()
    }
  })
}

function submit() {
  if (resourceUrl.value.length < 1) return uni.showToast({
    title: '请上传附件',
    icon: 'none'
  })
  let param = {
    trainingCourseId: detail.value.id,
    teacherId: detail.value.trainingId,
    homeworkName: resourceUrlName.value,
    homeworkUrl: resourceUrl.value
  }
  uni.showLoading('提交中...')
  addHomework(param).then((res) => {
    uni.hideLoading()
    if (res.code !== 200) {
      return uni.showToast({
        title: res.msg || '提交失败',
        icon: 'none'
      })
    }
    resourceUrl.value = ''
    resourceUrlName.value = ''
    uni.showToast({
      title: '提交成功',
      icon: 'success'
    })
    homeworkList()
  })
}

</script>

<template>
  <view class="T_page">
    <view class="header">
      <view class="title">
        <text>{{detail.trainingTheme}}</text>
        <uni-tag style="flex-shrink: 0;" :text="courseStatus.isSubWork !== 1 ? '待提交' : '已完成'" size="small" :type="courseStatus.isSubWork !== 1 ? 'warning' : 'success'" />
      </view>
      <view class="time">
        <image src="/static/svg/time-full.svg" />
        <text>截止时间：{{detail.workEndTime}}</text>
      </view>
    </view>
    <view class="tips">
      <view>作业要求</view>
      <text>{{detail.workRequire}}</text>
    </view>
    <view class="file" v-if="showStartTimeButton">
      <view class="title">已上传附件</view>
      <view class="content">
        <view class="content_item" v-for="(item, index) in workList" :key="index">
          <view>{{item.homeworkName}}</view>
          <span class="download" @click="handleDownload(item.homeworkUrl)">下载</span>
        </view>
      </view>
      <view class="title" v-if="resourceUrl.length > 0">待上传附件</view>
      <view class="content" v-if="resourceUrl.length > 0">
        <view class="content_item">{{resourceUrlName}}</view>
      </view>
      <button class="submit" @click="upload" v-if="showEndTimeButton">上传附件</button>
      <!-- <button class="submit" @click="upload">上传附件</button> -->
    </view>
    <view style="padding-bottom: 50rpx;" v-if="showStartTimeButton && showEndTimeButton">
      <button class="submit" type="primary" @click="submit" >提交作业</button>
    </view>

  </view>
</template>

<style lang="scss" scoped>
.T_page {
  display: flex;
  flex-direction: column;
  gap: 30rpx;

  >view {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 30rpx;
  }
}

.header {
  >.title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 32rpx;
    font-weight: bold;
    color: #000;
  }

  >.time {
    margin-top: 20rpx;
    display: flex;
    align-items: center;
    gap: 10rpx;
    font-size: 24rpx;
    color: #6B7280;

    >image {
      width: 24rpx;
      height: 24rpx;
    }
  }
}

.tips {
  >view {
    color: #000;
    margin-bottom: 20rpx;
  }

  >text {
    display: block;
    color: #4B5563;
    font-size: 24rpx;
    line-height: 35rpx;
    margin-bottom: 10rpx;
  }
}

.file {
  >.title {
    color: #000;
    margin-bottom: 20rpx;
  }

  >.content {
    .content_item {
      padding: 8rpx 20rpx;
      box-sizing: border-box;
      border: 2rpx solid #dedede;
      border-radius: 20rpx;
      margin-bottom: 20rpx;
      display: flex;
      align-items: center;
      gap: 20rpx;
      view {
        flex: 1;
        word-break: break-all;
        word-wrap: break-word;
        overflow-wrap: break-word;
      }
      .download {
        color: #3b82f6;
      }
    }
  }
}
</style>
